

#include "unity.h"
#include "unity_fixture.h"

#include "Debug.h"
#include "BSP_Sleep.h"
#include "log/log2.h"
#include <phNfcLib_Initialization.h>
#include "Utility.h"
#include <Reader/Reader.h>

#include "Reader/reader_wavelynx_config.h"
#include "Reader/reader_samav3.h"
/*=========================================================================*/

// int reader_cfg_clac_mac(const uint8_t *keys, uint8_t* data, uint16_t len, uint8_t* mac);
static int samav3_reset_factory_key(void){
	int ret = 0;
	ret = samav3_disable_key_entry(SAM_KID_KFR0);
	if(ret){
		LOG2_ERR("samav3_reset_key_entry(%d) fail: %d", SAM_KID_KFR0, ret);
		return ret;
	}	
	ret = samav3_disable_key_entry(SAM_KID_KFRM);
	if(ret){
		LOG2_ERR("samav3_disable_key_entry(%d) fail: %d", SAM_KID_KMRM, ret);
		return ret;
	}
	ret = samav3_disable_key_entry(SAM_KID_KFR);
	if(ret){
		LOG2_ERR("samav3_disable_key_entry(%d) fail: %d", SAM_KID_KFR, ret);
		return ret;
	}
	ret = samav3_disable_key_entry(SAM_KID_KFM);
	if(ret){
		LOG2_ERR("samav3_disable_key_entry(%d) fail: %d", SAM_KID_KFM, ret);
		return ret;
	}
	return 0;
}

/*================================================================================================*/


TEST_GROUP(DesfireCfg);


TEST_SETUP(DesfireCfg)
{
	reader.hfFlags = TAG_MASK_MIFARE;
	Reader_NFC_LoadProfile(reader.hfFlags, 0, 0, 0);
}

TEST_TEAR_DOWN(DesfireCfg)
{
	Reader_NFC_RfOff();
}

// TEST(DesfireCfg, cmac)
// {
// 	const uint8_t keys[16] = {0};
// 	uint8_t data[16] = {0};
// 	uint8_t mac[16] = {0};

// 	int ret = reader_cfg_clac_mac(keys, data, 16, mac);	
// 	TEST_ASSERT_EQUAL_INT(0, ret);
// 	LOG2_BUF_DBG("mac", mac, 16);
// }

int reader_cfg_load_default_key(void);
int reader_wavelynx_config3(SimpleTag_T* tag);
int reader_wavelynx_init(void);

TEST(DesfireCfg, read_active_card)
{
	int ret = 0;
	credential_t cred;
	reader_wavelynx_init();
	reader_wavelynx_config_init();
	ret = samav3_init();
	TEST_ASSERT_EQUAL_INT(0, ret);
	ret = samav3_activate();
	TEST_ASSERT_EQUAL_INT(0, ret);
	// samav3_reset_factory_key();
	ret = reader_cfg_load_default_key();
	TEST_ASSERT_EQUAL_INT(0, ret);
	while(1){
		Reader_NFC_RfOff();
		BSP_Sleep_Ms(500);
		ret = Reader_NFC_DiscoveryStd3(&cred.tag, PHAC_DISCLOOP_POS_BIT_MASK_A, 5);
		if(!ret){
			reader_wavelynx_config3(&cred.tag);
		}
	}
}


